package com.rabbit.workqueue;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by IntelliJ IDEA.
 * <p>
 * Author: libingyang
 * Date: 2021-03-15 17:00
 */
public class Consumer {


    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory factory = new ConnectionFactory();


        factory.setHost("192.168.100.54");

        factory.setPort(5672);

        factory.setVirtualHost("/");

        factory.setUsername("guest");

        factory.setPassword("guest");

        // 获取连接对象
        Connection connection = factory.newConnection();


        // 获取连接通道
        Channel channel = connection.createChannel();

        // 每次只能消费一个
        channel.basicQos(1);

        // 通道绑定消息队列
        /**
         * 参数
         * 1 队列名称，队列不存在 自动创建
         * 2 用来定义队列是否要持久化
         * 3 是否是独占队列
         * 4 是否在消费完成删除队列
         * 5 额外附加参数
         */
        channel.queueDeclare("task_queue", true, false, false, null);

        channel.basicConsume("task_queue",false, new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


                System.out.println(new String(body));
//
                // 参数 1：手动确认消息标识 每次确认一个  2 ：是否批量处理.true:将一次性ack所有小于deliveryTag的消息
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });

//        channel.close();
//        connection.close();
    }
}
